import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

// const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist
async function addRoute() {
  const accessRoutes = await store.dispatch('permission/generateRoutes', '')
  router.addRoutes(accessRoutes)
}
addRoute()
router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()
  // set page title
  document.title = getPageTitle(to.meta.title)
  // determine whether the user has logged in
  const hasToken = getToken()
  const hasUser = store.getters.name
  if (to.meta.auth) {
    if (hasUser) {
      next()
    } else {
      if (hasToken) {
        // 验证token
        try {
          // ok
          await store.dispatch('user/getInfo')
          next({ ...to, replace: true })
        } catch (e) {
          // 失败
          await store.dispatch('user/resetToken')
          Message.error('已过期')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      } else {
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      }
    }
  } else {
    if (to.path === '/login' && hasUser) {
      next({ path: '/' })
    } else {
      next()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
